package moo.stargalaxy_bukkit.api;

import com.alibaba.fastjson.JSONObject;
import moo.stargalaxy_bukkit.StarGalaxy_Bukkit;
import moo.stargalaxy_bukkit.config.Config;
import moo.stargalaxy_bukkit.data.BukkitStarGalaxyData;
import moo.stargalaxy_bukkit.utils.CommandUtil;
import moo.stargalaxy_bukkit.utils.Lag;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissionAttachmentInfo;
import org.bukkit.scheduler.BukkitRunnable;

import java.util.UUID;
import java.nio.charset.StandardCharsets;


public class GalaxyBukkitAPI {
    public static boolean addTpCoolDown(Player proxiedPlayer){
        if(BukkitStarGalaxyData.getCoolDownMap().containsKey(proxiedPlayer.getUniqueId())){
            proxiedPlayer.sendMessage(Config.getConfiguration().getString("Message_Set.GoServer_Cooldown"));
            return false;
        } else {
            BukkitStarGalaxyData.getCoolDownMap().put(proxiedPlayer.getUniqueId(), true);
            new BukkitRunnable() {
                @Override
                public void run() {
                    BukkitStarGalaxyData.getCoolDownMap().remove(proxiedPlayer.getUniqueId());
                }
            }.runTaskLaterAsynchronously(StarGalaxy_Bukkit.getPlugin(), 20L * Config.getConfiguration().getInt("Server_Set.Cross_Delaytime"));
            return true;
        }
    }

    public static void checkJoin(Player player){
        double tps = Config.getConfiguration().getDouble("Server_Set.TPS_JoinLimit");
        if(tps != 0 && Lag.getTPS() < tps){
            player.kickPlayer("§7无法进入.服务器流畅度低于限制: §6" + tps);
            return;
        }
        // lag为限时百分比
        // double lag = Math.round((1.0D - tps / 20.0D) * 100.0D);
        if(!player.hasPlayedBefore()){
            if(player.isOp()){
                for (String s : Config.getConfiguration().getStringList("Command_Set.Admin_First_Join")) {
                    CommandUtil.executeCommand(player, s);
                }
            } else {
                for (String s : Config.getConfiguration().getStringList("Command_Set.Player_First_Join")) {
                    CommandUtil.executeCommand(player, s);
                }
            }
        } else {
            if(player.isOp()){
                for (String s : Config.getConfiguration().getStringList("Command_Set.Admin_Ord_Join")) {
                    CommandUtil.executeCommand(player, s);
                }
            } else {
                for (String s : Config.getConfiguration().getStringList("Command_Set.Player_Ord_Join")) {
                    CommandUtil.executeCommand(player, s);
                }
            }
        }
        //player.getServer().spigot().
    }

    public static void checkQuit(Player player){
        if(player.isOp()){
            for (String s : Config.getConfiguration().getStringList("Command_Set.Admin_Ord_Quit")) {
                CommandUtil.executeCommand(player, s);
            }
        } else {
            for (String s : Config.getConfiguration().getStringList("Command_Set.Player_Ord_Quit")) {
                CommandUtil.executeCommand(player, s);
            }
        }
    }

    public static boolean canUseTemplates(Player player, String name){
        if(player.isOp()){
            return true;
        }
        if(player.hasPermission("sgs.createserver.templates.*")){
            return true;
        }
        return player.hasPermission("sgs.createserver.templates." + name);
    }

    public static boolean canDelete(Player player, String name){
        if(player.isOp()){
            return true;
        }
        if(player.hasPermission("sgs.deleteserver.*")){
            return true;
        }
        boolean b = player.hasPermission("sgs.deleteserver." + name);
        if(!b){
            player.sendMessage("§7缺少所需权限: §6sgs.deleteserver." + name +" §7或 §6sgs.deleteserver.*");
        }
        return b;
    }

    public static boolean canRestart(CommandSender player, String name){
        if(player.isOp()){
            return true;
        }
        if(player.hasPermission("sgs.restartserver.*")){
            return true;
        }
        boolean b = player.hasPermission("sgs.restartserver." + name);
        if(!b){
            player.sendMessage("§7缺少所需权限: §6sgs.restartserver." + name +" §7或 §6sgs.restartserver.*");
        }
        return b;
    }

    public static boolean canJoin(CommandSender player, String name){
        if(player.isOp()){
            return true;
        }
        if(player.hasPermission("sgs.crosserverfid_normal.*")){
            return true;
        }
        boolean b = player.hasPermission("sgs.crosserverfid_normal." + name);
        if(!b){
            player.sendMessage("§7缺少所需权限: §6sgs.crosserverfid_normal." + name +" §7或 §6sgs.crosserverfid_normal.*");
        }
        return b;
    }

    public static int getCanCreateServer(Player player){
        for (PermissionAttachmentInfo effectivePermission : player.getEffectivePermissions()) {
            String permission = effectivePermission.getPermission();
            if(permission.contains("sgs.createserver.snumber.")){
                return Integer.parseInt(permission.substring(25).trim());
            }
        }
        return 0;
    }

    public static void gitServerInfo(){
        new BukkitRunnable() {
            @Override
            public void run() {
                if(Config.getConfiguration().getBoolean("Server_Set.Updata_RunSataus")){
                    GalaxyAPI.gitServerData(
                            Config.getConfiguration().getString("Server_Set.Server_Fid"),
                            String.valueOf(Bukkit.getOnlinePlayers().size()),
                            String.valueOf(Bukkit.getMaxPlayers()),
                            String.valueOf(Lag.getTPS()),
                            Config.getConfiguration().getString("Server_Set.TPS_JoinLimit")
                    );
                }
            }
        }.runTaskTimerAsynchronously(StarGalaxy_Bukkit.getPlugin(), 100, 1200);
    }

    public static void initGalaxy(){
        GalaxyAPI.url = "http://" + Config.getConfiguration().getString("StarGalaxy_Link.IP") + ":" + Config.getConfiguration().getString( "StarGalaxy_Link.PORT");
        GalaxyAPI.key = Config.getConfiguration().getString("StarGalaxy_Link.SECRETKEY");
        // StarGalaxy_Bukkit.getPlugin().getLogger().info("┃     ██████╗  █████╗ ██╗      █████╗ ██╗  ██╗██╗   ██╗");
        // StarGalaxy_Bukkit.getPlugin().getLogger().info("┃    ██╔════╝ ██╔══██╗██║     ██╔══██╗╚██╗██╔╝╚██╗ ██╔╝");
        // StarGalaxy_Bukkit.getPlugin().getLogger().info("┃    ██║  ███╗███████║██║     ███████║ ╚███╔╝  ╚████╔╝ ");
        // StarGalaxy_Bukkit.getPlugin().getLogger().info("┃    ██║   ██║██╔══██║██║     ██╔══██║ ██╔██╗   ╚██╔╝  ");
        // StarGalaxy_Bukkit.getPlugin().getLogger().info("┃    ╚██████╔╝██║  ██║███████╗██║  ██║██╔╝ ██╗   ██║   ");
        // StarGalaxy_Bukkit.getPlugin().getLogger().info("┃     ╚═════╝ ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═╝  ╚═╝   ╚═╝   ");
        // StarGalaxy_Bukkit.getPlugin().getLogger().info("┃                                                    ");
        Bukkit.getConsoleSender().sendMessage("§f┃  ");
        Bukkit.getConsoleSender().sendMessage("§f┃  ");
        Bukkit.getConsoleSender().sendMessage("§f┃§6      ______      _____     __        _____     __  __    __  __   ");
        Bukkit.getConsoleSender().sendMessage("§f┃§e     /_/\\___\\    /\\___/\\   /\\_\\      /\\___/\\  /\\  /\\  /\\/\\  /\\  /\\ ");
        Bukkit.getConsoleSender().sendMessage("§f┃§6     ) ) ___/   / / _ \\ \\ ( ( (     / / _ \\ \\ \\ \\ \\/ / /\\ \\ \\/ / / ");
        Bukkit.getConsoleSender().sendMessage("§f┃§e    /_/ /  ___  \\ \\(_)/ /  \\ \\_\\    \\ \\(_)/ /  \\ \\  / /  \\ \\__/ /  ");
        Bukkit.getConsoleSender().sendMessage("§f┃§6    \\ \\ \\_/\\__\\ / / _ \\ \\  / / /__  / / _ \\ \\  / /  \\ \\   \\__/ /   ");
        Bukkit.getConsoleSender().sendMessage("§f┃§e     )_)  \\/ _/( (_( )_) )( (_____(( (_( )_) )/ / /\\ \\ \\  / / /    ");
        Bukkit.getConsoleSender().sendMessage("§f┃§6     \\_\\____/   \\/_/ \\_\\/  \\/_____/ \\/_/ \\_\\/ \\/__\\/__\\/  \\/_/    ");
        Bukkit.getConsoleSender().sendMessage("§f┃  ");
        Bukkit.getConsoleSender().sendMessage("§f┃  ");
        Bukkit.getConsoleSender().sendMessage("§f┃    §8●   初始化：§7本插件版本 §8( §f" + Config.version + "§8 )");
        Bukkit.getConsoleSender().sendMessage("§f┃    §8●   初始化：§d自定义指令 §8( §f" + BukkitStarGalaxyData.getQuickCmd().size() + " 条§8 )");
        Bukkit.getConsoleSender().sendMessage("§f┃    §8●   初始化：§e控制台地址 §8( §f" + Config.getConfiguration().getString("StarGalaxy_Link.IP") + "§8 )");
        Bukkit.getConsoleSender().sendMessage("§f┃    §8●   初始化：§e控制台端口 §8( §f" + Config.getConfiguration().getString( "StarGalaxy_Link.PORT") + "§8 )");
        try {
            JSONObject serverTemplates = GalaxyAPI.getServerTemplates();
            if(serverTemplates.getInteger("code") == 1){
                Bukkit.getConsoleSender().sendMessage("§f┃    §8●   初始化：§a控制台已连接");
            } else {
                Bukkit.getConsoleSender().sendMessage("§f┃    §8●   初始化：§c控制台未连接");
            }
            Bukkit.getConsoleSender().sendMessage("§f┃  ");
            Bukkit.getConsoleSender().sendMessage("§f┃  ");
        } catch (Exception e) {
            Bukkit.getConsoleSender().sendMessage("§f┃    §8●   初始化：§c群星连接失败.请检查配置文件");
        }
    }

    // 计算玩家UUID算法(v3离线算法) 独立UUID算法
    public static String GetUuidv3Name(String name, boolean Fromt){
        // UUID uuid = UUID.nameUUIDFromBytes((str.getBytes("UTF-8")));
        UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(StandardCharsets.UTF_8));
        String Textuuid = uuid.toString();
        // 判断是否格式化
        if (!Fromt) {
            return Textuuid.replaceAll("-", "");
        } else {
            return Textuuid;
        }

    }



}
